package com.team9.fitness.mapper;

import com.team9.fitness.entity.PostFavorite;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 帖子喜欢数据访问层接口
 * 
 * 提供帖子喜欢数据的CRUD操作：
 * - 喜欢管理：添加、更新、删除喜欢记录
 * - 查询功能：支持按用户、帖子、状态查询
 * - 统计功能：统计帖子的喜欢数量
 * - 状态管理：支持喜欢、取消喜欢状态切换
 */
@Mapper
public interface PostFavoriteMapper {

    @Insert("INSERT INTO post_favorite (user_id, post_id, is_favorited, created_at) " +
            "VALUES (#{userId}, #{postId}, #{isFavorited}, NOW()) " +
            "ON DUPLICATE KEY UPDATE is_favorited = #{isFavorited}, created_at = NOW()")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertOrUpdate(PostFavorite postFavorite);

    @Select("SELECT * FROM post_favorite WHERE id = #{id}")
    PostFavorite selectById(Long id);

    @Select("SELECT * FROM post_favorite WHERE user_id = #{userId} AND post_id = #{postId}")
    PostFavorite selectByUserIdAndPostId(Long userId, Long postId);

    @Select("SELECT * FROM post_favorite WHERE post_id = #{postId} AND is_favorited = TRUE")
    List<PostFavorite> selectFavoritedByPostId(Long postId);

    @Select("SELECT * FROM post_favorite WHERE user_id = #{userId} AND is_favorited = TRUE")
    List<PostFavorite> selectFavoritedByUserId(Long userId);

    @Select("SELECT COUNT(*) FROM post_favorite WHERE post_id = #{postId} AND is_favorited = TRUE")
    int countFavoritesByPostId(Long postId);

    @Select("SELECT COUNT(*) FROM post_favorite WHERE user_id = #{userId} AND is_favorited = TRUE")
    int countFavoritesByUserId(Long userId);

    @Update("UPDATE post_favorite SET is_favorited = #{isFavorited}, created_at = NOW() " +
            "WHERE user_id = #{userId} AND post_id = #{postId}")
    int updateFavoriteStatus(Long userId, Long postId, Boolean isFavorited);

    @Delete("DELETE FROM post_favorite WHERE id = #{id}")
    int deleteById(Long id);

    @Delete("DELETE FROM post_favorite WHERE user_id = #{userId} AND post_id = #{postId}")
    int deleteByUserIdAndPostId(Long userId, Long postId);

    @Delete("DELETE FROM post_favorite WHERE post_id = #{postId}")
    int deleteByPostId(Long postId);
}
